import React, { Component } from 'react';
import Head from 'next/head';
import Router from "next/router";
import {notification ,Progress,message} from 'antd';
import Editor from '../../components/editor'
import MyHead from '../../components/head';
import * as API from '../../api/api'
import './index.less'
import auth from '../../lib/auth'
var timer;
export default class WriteComponent extends Component {
    static async getInitialProps (ctx) {
        auth(ctx)
        let editId = ctx.query.id;
        return {editId}
    }
    constructor(props) {
        super(props);
        this.state = {
            content: '',
            articleId: '',
            title: '',
            abstract:'',
            img:'',
            category:'',
            has_draft: false,
            isUpdate: false,
            allow_comment:true,
            categories:[],
            tags:[],
            uploadProgress:0,
            upload:false
            
        }

    }
    async componentWillMount() {
        let {editId} = this.props;
        if (editId) {
            await this.getArticle()
        } else {
            await this.getDrafts()
        }
        await this.getCateAndTag()
    }   
    componentWillUnmount() {
        clearTimeout(timer)
    }
    getArticle() {
        let {editId} = this.props;
        API.getArticleById({id:editId}).then(res=>{
            if (res.data.code === 1) {
                this.setState({
                    articleId: res.data.data._id,
                    img:res.data.data.img,
                    title: res.data.data.title,
                    content: res.data.data.content,
                    abstract:res.data.data.abstract,
                    category: res.data.data.category,
                    // allow_comment:res.data.data.allow_comment,
                    isUpdate:true
                })
            }
        })
    }
    //获取草稿
    getDrafts() {
        API.getDrafts().then(res=>{
            if (res.data.code === 1) {
                if (res.data.has_draft) {
                    let data = res.data.data[0]
                    this.setState({
                        articleId: data._id,
                        title: data.title,
                        content:data.content,
                        abstract:data.abstract,
                        has_draft:res.data.has_draft
                    })
                    notification['warning']({
                        // title:'警告',
                        message: '您上次还有未编辑的文章',
                        duration:2.5
                    });
                }
            }
        })
    }
    //保存草稿
    saveDraft() {
        let article={
            _id:this.state.articleId,
            content:this.refs['editor'].getEditorValue()
        }
        if(article.content){
            API.createDraft(article).then(res => {
                if (res.data.code === 1) {
                    this.setState({
                        articleId:res.data.id,
                        has_draft:res.data.has_draft
                    })
                    notification['success']({
                        message: '保存成功',
                        description:`保存于 ${res.data.time}`,
                        duration:2.5
                    });
                }
            })
        }
    }
    //监听标题和内容的变化，如有改动触发保存请求
    watchDraftChange=()=>{
        if(timer){
            clearTimeout(timer)
        }
        timer = setTimeout(()=>{
            this.saveDraft()
        },5000)
    }
    //上传图片
    uploadImg=(file,callback)=> {
        if (file == null) {
            return;
        }
        const isLt2M = file.size / 1024 / 1024 < 5;
        if (!isLt2M) {
            message.error('请上传小于5M的图片');
            return;
        }
        this.setState({
            upload:true
        })
        var formData = new FormData();
        formData.append('file',file);
        API.uploadImage(formData,(progressEvent)=>{
            let progress = (progressEvent.loaded / progressEvent.total * 100 | 0) 
            this.setState({
                uploadProgress:progress
            })
        }).then(res=>{
            if(res.data.code===1){
                if(callback&&typeof callback === 'function'){
                    callback(res.data.url)
                    this.setState({
                        upload:false,
                        uploadProgress:0
                    })
                }
            }else{
                message.error(res.data.message);
            }
        })
    }
    getCateAndTag() {
        API.getCateAndTag().then(res => {
            if (res.data.code === 1) {
                let {categories,tags} = res.data;
                this.setState({
                    categories,
                    tags
                })
            }
        })
    }
    //选择标签
    onSelectTag = (val) => {
        if(val.length){
            if(val.length<4){
                var lastTag = val[val.length-1];
                if (lastTag.length > 10) {
                    message.error('请输入不得超过10个字符');
                    val.pop()
                }
            } else {
                message.error('最多只能选择3个标签');
                val.pop()
            }
        }
    }
    //是否允许评论
    onChangeAllowCmt = (checked) => {
        this.setState({
            allow_comment:checked
        })
    }
    //发布
    handlePublish = () => {
        clearTimeout(timer)
        const {articleId,title,abstract,category,img} = this.state;
        const content = this.refs['editor'].getEditorValue();
        if (!title){
            message.error('标题不可为空哦^_^');
            return;
        }
        if (!content){
            message.error('亲，您忘记输入内容了呢^_^');
            return;
        }
        if (!category){
            message.error('选择一个文章类型吧^_^');
            return;
        }
        let body = {
            title,
            abstract,
            content,
            category,
            img
        }
        if (articleId){         //说明文章可能是草稿或者需要修改的文章
            body._id = articleId;
        }
        API.createArticle(body).then((res)=>{
            if (res.data.code === 1) {
                message.success(res.data.message);
                window.location.reload()
            } 
        })
    }
    handleRemove = () => {
        let {articleId} = this.state;
        API.removeArticle(articleId).then((res)=>{
            if (res.data.code === 1) {
                message.success(res.data.message);
                Router.push('/')
            } 
        })
    }
    //表单提交
    handleSubmit = (e) => {
        e.preventDefault();
        this.handlePublish()
    }
    handleInputChange=(e)=>{
        var newState = {};
        newState[e.target.name]=e.target.value;
        this.setState(newState);
    }
    handleUploadCover=(e)=>{
        var file = e.target.files[0]
        this.uploadImg(file,(url)=>{
            this.setState({
                img:url
            })
        })
    }
    handleRemovePicture=(e)=>{
        this.setState({
            img:''
        })
    }
    render() {
        const {categories,category,img,uploadProgress,upload,title,abstract,articleId} = this.state;
        return (
            <div className="write-layout">
                <MyHead/>
                <Head>
                    <title>写文章</title>
                </Head>
                {upload?(
                    <div className="uploadProgress-dialog fixed">
                        <div className="uploadProgress-inner">
                            <Progress width={60} type="circle" percent={uploadProgress} />
                        </div>
                    </div>
                ):null}
                <div className="write-header">
                    <div className="write-navbar fixed">
                        <div className="navbar-logo"></div>
                        <div className="navbar-middle">
                            <div className="navbar-title">
                                <div className="title">写文章</div>
                                <div className="sub-title"></div>
                            </div>
                        </div>
                        <div className="navbar-function">
                            <select name="category" value={category} onChange={this.handleInputChange}>
                                <option value='' disabled style={{display: 'none'}}>选择一个类型</option>
                                {   
                                    categories.map((item)=>{
                                        return (
                                            <option key={item.key} value={item.name}>{item.name}</option>
                                        )
                                    })
                                    
                                }
                            </select>
                            {articleId?(
                                <button onClick={this.handleRemove} className="write-btn write-publish-btn" type="button">删除</button>
                            ):''}
                            <button onClick={this.handleSubmit} className="write-btn write-publish-btn" type="button">发布</button>
                        </div>
                    </div>
                </div>
                <div className="write-body">
                    <div className="write-imgCover-wrp">
                        {
                            img?(
                                <div className="UploadPicture-preview">
                                    <img src={img} alt=""/>
                                    <div className="UploadPicture-buttons">
                                        <span onClick={this.handleRemovePicture}>删除</span>
                                    </div>
                                </div>
                            ):(
                                <label className="UploadPicture-wrapper">
                                    <input onChange={this.handleUploadCover} type="file" accept=".jpeg, .jpg, .png" className="UploadPicture-input"/>
                                    <i className="WriteCover-uploadIcon icon-ic_phot_camera_alt"></i> 
                                </label>
                            )
                        }
                    </div>
                    <div className="write-form">
                        <div className="write-input-title">
                            <textarea value={title} onChange={this.handleInputChange} name="title" className="input" placeholder="请输入标题（最多 50 个字）">
                            </textarea>
                        </div>
                        <div className="write-input-summary">
                            <textarea value={abstract} onChange={this.handleInputChange} name="abstract" className="input" placeholder="简介（ 50 个字）"></textarea>
                        </div>
                    </div>
                    <div className="write-editor">
                        <Editor ref="editor" 
                        uploadImg={this.uploadImg}
                        onEditorValueChange={this.watchDraftChange}
                        content={this.state.content}/>
                    </div>
                </div>
            </div>
        );
    }
}
